package com.hoas.api.core.entity.api;

import java.io.IOException;
import java.util.Map;

import com.hoas.api.core.intf.ApiProcesser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import  com.hoas.api.core.exception.BusinessApiCreateException;
import  com.hoas.api.core.exception.BusinessProcessException;
import  com.hoas.api.core.util.HttpClientUtil;

public class HttpRequestBusinessApi extends BusinessApi implements ApiProcesser {
	
	private Logger logger = LoggerFactory.getLogger(HttpRequestBusinessApi.class);

	public HttpRequestBusinessApi(String businessId) throws BusinessApiCreateException {
		super(businessId);
	}
	
	/**
	 * 请求URL地址
	 */
	private String url;
	
	private String method = "GET";
	
	private String forceEncoding = "UTF-8";
	
	private String contentType = "text";
	
	public String getUrl() {
		return url;
	}
	
	public void setUrl(String url) {
		this.url = url;
	}
	
	public String getMethod() {
		return method;
	}
	
	public void setMethod(String method) {
		this.method = method;
	}
	
	public String getForceEncoding() {
		return forceEncoding;
	}
	
	public void setForceEncoding(String forceEncoding) {
		this.forceEncoding = forceEncoding;
	}
	
	public String getContentType() {
		return contentType;
	}
	
	public void setContentType(String contentType) {
		this.contentType = contentType;
	}

	@Override
	public Object process(Map<String, Object> parameter) throws BusinessProcessException {
		String resp = null;
		try {
			if("GET".equals(method)) {
				String tempUrl = new String(url);
				if(parameter != null && parameter.size() > 0) {
					StringBuffer param = new StringBuffer(url + "?");
					for(String key : parameter.keySet()) {
						param.append(key + "=" + parameter.get(key)).append("&");
					}
					tempUrl = param.substring(0, param.length() - 1);
				}
				resp = HttpClientUtil.get(tempUrl, null, forceEncoding);
			} else if("POST".equals(method)) {
				resp = HttpClientUtil.post(url, null, parameter, forceEncoding);
			}
			
			return resp;
		} catch (IOException e) {
			logger.error("请求异常", e);
		}
		return null;
		
	}

}
